import * as api from '@/api/sc_goods'
import { freightTemplateList } from '@/api/sc_other.js'
export default {
  data() {
    return {
      classlistAlias: { // 二级菜单序列化
        children: 'subList', value: "id", label: "name",
      },
      restaurants: [],
      classlist: [], // 系统分类
      busClassList: [], // 店内分类
      isShowBusClass: false, // 新增店内分类弹窗
      busClassName: '', // 新增店内分类
      formatList: [], // 所有的规格和属性
      payMethoy: [{label:'快递发货', value: '1' }, {label:'到店自取', value: '2' }], // 配送方式
      params: {
        activesku:[],// 临时SKU
        goodsSkus:[],
        typeId: [], // 系统分类
        goodsName: '', // 商品名称
        goodsNum: '', // 商品编号
        // Desc: '', // 买点
        shopTypeId: '', // 店内分类
        goodsDesc: '', //  商品详情
        goodsImg: [], // 商品图片
        // tags: [], // 商品标签
        distributionmodestr: [], // 配送方式
        freightfMode: 1, // 运费方式
        freightTemplateId: null, // 运费模板
        freight: 0,// 快递运费
        price: undefined, // 商品价格
        // scribing: undefined, // 划线价
        cost: undefined, // 市场价格
        stock: 0, // 库存
        saleCount: 0, // 虚拟销量
        groundingMode: 1, // 上架方式
        groundingDate: '', // 上架时间
        showStock: false, // 是否显示库存
        hasImage: false // 是否上传规格图片
      },
      isSetImg: false, // 是否添加规格图片
      // 新进规格属性相关
      isShowOpenSubSku: false, // 弹出框
      isShowOpenSku: false, // 新增新的规格
      isSubmitButton: false, // 提交等待
      subSkuEdit: null, // 操作的规格属性
      subTitleName: '', // 规格属性名称
      top: null,
      left: null,
      busId: null, // 商家id
      goodsId: null, // 商品id
      isShowPhoto: false, // 显示相册
      upImgMarker: null, // 上传图片标记
      setSkuImgIndex: null, // 规格图片的位置
      isShowGoodsDisc: false, // 商品详情
      freightTemplateList: [],
      reastLoading: false // 刷新运费模板按钮控制
    }
  },
  filters: {
    showTtitle(arr) { // 过滤有id的规格属性
      if (arr && arr.length) {
        return arr.filter(item =>{
          return item.id && item.sid && item.sid.length && !item.sid.every(list => !list.id)
        })
      } else {
        return []
      }
    },
    filterSku(arr, actSku, id) { // 过滤已选的规格
      if (arr && arr.length && actSku && actSku.length) {
        const newArr = arr.filter(item => {
          return actSku.findIndex(list => (list.id === item.id && list.id !== id)) === -1
        })
        return newArr
      } else {
         return arr || []
      }
    },
    getSubOption(arr, id, sid, item) { // 过滤已选的规格值
      const l = arr.findIndex(e => e.id === id)
      const newArr = l > -1 ? arr[l].goodsPropertyValues : []
      if (newArr.length) {
        return newArr.filter(list => {
          return item.findIndex(m => list.id === m.id && m.id !== sid) === -1
        })
      } else {
        return []
      }
    }
  },
  computed: {
    choseSubFormatList() { // 序列化组合
      const subArr = [] // 规格值的组合
      this.params.activesku.forEach(item => {
        const id = item.id
        const subIds = item.sid.filter(e => e.id)
        if (id && subIds.length) {
          const arr = []
          subIds.forEach(list => {
            arr.push({ id:list.id, name: list.name })
          })
          subArr.push(arr)
        }
      })
      /*笛卡尔积*/
      if(subArr.length) {
        const descartes =(array) =>{
          if( array.length < 2 ) return array[0].map(item => [item]) || []
          return [].reduce.call(array, function(col, set) {
            var res = []
            col.forEach(function(c) {
              set.forEach(function(s) {
                var t = [].concat(Array.isArray(c) ? c : [c])
                t.push(s)
                res.push(t)
            })})
            return res
          })
        }
        return descartes(subArr)
      } else {
        return []
      }
    }
  },
  watch: {
    choseSubFormatList: { // 计算属性不可更改 监听规格重新赋值一个属性
      handler(val, old) {
        console.log(val)
        if (this.goodsId && old.length === 0) {
          
        } else {
          this.params.goodsSkus = val.map(item => {
            return {
              ids: item, price: undefined, cost: undefined, goodsnum: '', salesvolume: 0, stock: undefined
            }
          })
        }
      },
      deep: true
    }
  },
  methods: {
    telAndMobile(rule, value, callback) { //商品编号校验
      if (!(/^((0\d{2,3}-\d{7,8})|(1[0123456789]\d{9}))$/).test(value)) {
        callback(new Error('手机号码或座机号码有误，请重填!'))
      } else {
        callback()
      }
    },
    valActivesku(rule, value, callback) { // sku 商品信息校验
      if (value.length) {
        for (let i = 0; i< value.length; i++) {
          const item = value[i]
          if (item.id) {
            if (item.sid && item.sid.length) {
              for (let k = 0; k < item.sid.length; k++) {
                const list = item.sid[k]
                if (list.id) {
                  if (this.params.hasImage && i === 0) {
                    if (!list.img) {
                      callback(new Error('请为属性添加图片!'))
                      break
                    }
                  }
                } else {
                  callback(new Error('有属性值未选值!'))
                  break
                }
              }
            } else {
              callback(new Error('有规格未添加属性!'))
              break
            }
          } else {
            callback(new Error('有规格未选值!'))
            break
          }
        }
        callback()
      } else {
        callback()
      }
    },
    valGoodsSkus(rule, value, callback) { // 校验规格明细
      if (value.length) {
        for (let i = 0; i < value.length; i++) {
          const item = value[i]
          if (item.price > 0) {}
          else {
            callback(new Error('有价格未填或小于0!'))
            break
          }
          if (item.stock >= 0) {}
          else {
            callback(new Error('库存未填!'))
            break
          }
        }
        callback()
      } else {
        callback()
      }
    },
    openImgDialog(type, index) { // 打开上传图片，标记要上传的位置
      this.upImgMarker = type
      if (type === 2) {
        this.setSkuImgIndex = index
      }
      this.isShowPhoto = true
    },
    choseImg(img) { // 选择图片
      this.isShowPhoto = false
      if (this.upImgMarker === 1) {
        this.params.goodsImg.push(img)
      } else if (this.upImgMarker === 2) {
        this.params.activesku[0].sid[this.setSkuImgIndex].img = img
      }
    },
    chooseTemplate(content) { // 设置商品详情模板
      this.params.goodsDesc = content
      this.isShowGoodsDisc = false
    },
    updateData(content) { // 手动输入模板
      console.log(content)
      this.params.goodsDesc = content
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      //console.log({ row, column, rowIndex, columnIndex })
      const arr = this.$options.filters.showTtitle(this.params.activesku).map(list => {
        return {...list, ...{ sid: list.sid.filter(i => i.id)} }
      })
      if (arr.length >= 2) {
        const l = arr.length
        for (let i = 0; i< l -1; i++) {
          let num = 1
          for (let s = i + 1; s < arr.length; s++) {
            num = num * arr[s].sid.length
          }
          if (columnIndex == i) {
            if (rowIndex % num === 0) {
              return [num, 1]
            } else {
              return [0, 0]
            }
          }
        }
      } else {
        return
      }
    },
    addMoreSku() { // 本地添加规格
      this.params.activesku.push({ id: null, name: '', sid: []})
    },
    addMoreSkuSub(index) { // 本地添加规格值
      this.params.activesku[index].sid.push({id: null, name: '', img: ''})
    },
    delSubSku(index, l) {
      this.params.activesku[index].sid.splice(l, 1)
    },
    delSku(index) {
      this.params.activesku.splice(index, 1)
    },
    getAllFormat() { // 获取所有规格属性
      api.selectPropertyName({ businessId: this.busId }).then(res => {
        if (res.success) {
          this.formatList = res.data
        }
      })
    },
    addNewsku($el) { // 新建新的规格
      this.subTitleName = ''
      this.left = $el.clientX
      this.top = $el.clientY
      this.isShowOpenSku = true
    },
    opSubSku($el, id) { // 打开子规格属性
      this.subSkuEdit = id
      this.subTitleName = ''
      this.left = $el.clientX
      this.top = $el.clientY
      this.isShowOpenSubSku = true
    },
    changeKuaid(val) { // 快递方式
      if (val === 1) {
        this.params.yunfen = 0
      } else if (val === 2) {
        this.params.model = ''
      }
    },
    changeFormt() { // 切换规格 过滤新增的规格
      if (this.subTitleName) {
        const s = this.formatList.findIndex(item => {
          return item.name === this.subTitleName
        })
        if (s === -1) {
          this.isSubmitButton = true
          api.savePropertyName({ businessId: this.busId, name: this.subTitleName}).then(res => {
            if (res.success) {
              this.formatList = res.data
              this.isShowOpenSku = false
            }
          }).finally(() => { this.isSubmitButton = false })
        } else {
          this.$message.error('改规格已存在相同！')
        }
      } else {
        this.$message.error('请输入规格！')
      }
    },
    setSku(val, index) { // 选择规格后对应名称
      this.params.activesku[index].sid = []
      const s = this.formatList.findIndex(item => item.id === val)
      if (s > -1) this.params.activesku[index].name = this.formatList[s].name
    },
    setSunSku(val, index, id, s) { // 设置规格属性
      const l = this.formatList.findIndex(item => item.id === id)
      const sIndex = this.formatList[l].goodsPropertyValues.findIndex(item => item.id === val)
      this.params.activesku[index].sid[s].name = this.formatList[l].goodsPropertyValues[sIndex].name
    },
    changeSubFormt() { // 添加规格属性
      if (this.subTitleName) {
        const index = this.formatList.findIndex(item => item.id == this.subSkuEdit)
        const passVal = this.formatList[index].goodsPropertyValues
        const s = passVal.findIndex(l => l.name == this.subTitleName)
        if (s === -1) {
          const params = {
            businessId: this.busId,
            goodsPropertyValues: [{nameid: this.subSkuEdit, name: this.subTitleName }]
          }
          this.isSubmitButton = true
          api.savePropertyValue(params).then(res => {
            if (res.success) {
              this.formatList = res.data
              this.isShowOpenSubSku = false
            }
          }).finally(() => { this.isSubmitButton = false })
        } else {
          this.$message.error('改规格属性已存在相同！')
        }
      } else {
        this.$message.error('请输入规格属性！')
      }
    },
    getGoodsClassList(businessid) { // 店内分类列表
      api.goodsClassSelect({businessid}).then(res => {
        if (res.success) {
          this.busClassList = res.data
        }
      })
    },
    addBusClass() { // 新减商品分类
      this.busClassName = ''
      this.isShowBusClass = true
    },
    subMitBusClass(formName) { // 提交分类
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.isSubmitButton = true
          api.goodsClassSave({ businessid: this.busId, name: this.busClassName}).then(res => {
            if (res.success) {
              this.isShowBusClass = false
              this.getGoodsClassList(this.busId)
            }
          }).finally(() => {
            this.isSubmitButton = false
          })
        }
      })
    },
    getTypeClass() { // 获取系统分类
      api.classListSelect().then(res => {
        if (res.success) {
          const arr = res.data || []
          arr.forEach((item, index) => {
            if (item.subList.length == 0) {
              delete arr[index]
            } else {
              item.subList.forEach((list, index1) => {
                delete list.subList
              })
            }
          })
          this.classlist = arr
        }
      })
    },
    addNewTemplate() { // 去新建模板
      const { href } = this.$router.resolve({
        path: "/main/sc_shop/addDelivery",
        query: { id: this.$route.query.bid, add: 'true' }
      })
      window.open(href, '_blank')
    },
    submitForm(formName) { // 提交分类
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const params = { ...this.params }
          params.businessId = this.busId
          params.distributionmodestr = params.distributionmodestr.join(',') || ''
          if (this.goodsId) {
            params.id = this.goodsId
            api.goodsUpdate(params).then(res => {
              if (res.success) {
                this.$message.success('提交成功！')
                this.$router.back()
              }
            })
          } else {
            api.goodsSave(params).then(res => {
              if (res.success) {
                this.$message('提交成功！')
                this.$router.back()
              }
            })
          }
        } else {
          this.$message.error('页面有必填项未填写，请检查！')
        }
      })
    },
    getFreightTemplateList(reast) { // 获取运费模板列表
      const params = { businessId: this.busId, name: '' }
      this.reastLoading = Boolean(reast)
      freightTemplateList(params).then(res => {
        if (res.success) {
          this.freightTemplateList = res.data
          if (reast) {
            this.$message.success('运费模板数据已更新！')
          }
        }
      }).finally(() => this.reastLoading = false )
    },
    getGoodsInfo() { // 获取商家详情
      api.goodsInfo({ id: this.goodsId}).then(res => {
        if (res.success) {
          const params = res.data
          params.distributionmodestr = params.distributionmodestr ? params.distributionmodestr.split(','): []
          this.params = params
        }
      })
    }
  },
  mounted() {
    this.busId = this.$route.query.bid
    this.goodsId = this.$route.query.gid
    this.getAllFormat()
    this.getTypeClass()
    this.getGoodsClassList(this.busId)
    this.getFreightTemplateList()
    if (this.goodsId) {
      this.getGoodsInfo()
    }
    document.addEventListener('click', e => {
      this.isShowOpenSubSku = false
      this.isShowOpenSku = false
    }, false)
  }
}
